<?php

/**
 * TODO 基础分页的相同代码封装，使前台的代码更少
 * @param $m 模型，引用传递
 * @param $where 查询条件
 * @param int $pagesize 每页查询条数
 * @return \Think\Page
 */
function getpage(&$m, $where, $pagesize = 10) {
    //$m1=clone $m;//浅复制一个模型
    // $count = $m->where($where)->count();//连惯操作后会对join等操作进行重置
    // $m=$m1;//为保持在为定的连惯操作，浅复制一个模型
    $p = new Think\Page($m, $pagesize);
    $p->lastSuffix = false;
    $p->setConfig('header', '<li class="rows">共<b>%TOTAL_ROW%</b>条记录&nbsp;&nbsp;每页<b>25</b>条&nbsp;&nbsp;第<b>%NOW_PAGE%</b>页/共<b>%TOTAL_PAGE%</b>页</li>');
    $p->setConfig('prev', '上一页');
    $p->setConfig('next', '下一页');
    $p->setConfig('last', '末页');
    $p->setConfig('first', '首页');
    $p->setConfig('theme', '%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');

    $p->parameter = I('get.');

    // $m->limit($p->firstRow,$p->listRows);

    return $p;
}

function verificationCode($leng) {
    $arr = array_merge(range(0, 9));
    shuffle($arr);
    $str = implode('', array_slice($arr, 0, $leng));
    return $str;
}

function pr($params) {
    echo "------<br/>";
    print_r($params);
    echo "------<br/>";
    die();
}

function env() {
    if (env == 'dev') {
        setcookie('id', '2794');
    }
    return TRUE;
}

function where($key = '', $param) {
    $where = [];
    if (!empty($param)) {
        $where[$key] = $param;
    }
    return $where;
}

/**
 * 初始化redis
 *
 * @return void
 */
function redis() {
    $redis = new Redis();
    $conncet = $redis->connect(C('REDIS_HOST'), C('REDIS_PORT'));
    if ($conncet) {
        if (C('REDIS_AUTH'))
            $redis->auth(C('REDIS_AUTH'));
    }else {
        Think\Log::write('redis connect failed', 'ERR');
    }

    return $redis;
}

function get_ip($type = 0) {
    $type = $type ? 1 : 0;
    static $ip = NULL;
    if ($ip !== NULL)
        return $ip[$type];
    if (isset($_SERVER['HTTP_X_REAL_IP'])) {//nginx 代理模式下，获取客户端真实IP
        $ip = $_SERVER['HTTP_X_REAL_IP'];
    } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {//客户端的ip
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {//浏览当前页面的用户计算机的网关
        $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        $pos = array_search('unknown', $arr);
        if (false !== $pos)
            unset($arr[$pos]);
        $ip = trim($arr[0]);
    }elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip = $_SERVER['REMOTE_ADDR']; //浏览当前页面的用户计算机的ip地址
    } else {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    // IP地址合法验证
    $long = sprintf("%u", ip2long($ip));
    $ip = $long ? array($ip, $long) : array('0.0.0.0', 0);
    return $ip[$type];
}

function mb_unserialize($serial_str) {
    $serial_str = preg_replace('!s:(\d+):"(.*?)";!se', "'s:'.strlen('$2').':\"$2\";'", $serial_str);
    $serial_str = str_replace("\r", "", $serial_str);
    return unserialize($serial_str);
}

function mb_unserialize2($str) {
    return preg_replace_callback('#s:(\d+):"(.*?)";#s', function($match) {
        return 's:' . strlen($match[2]) . ':"' . $match[2] . '";';
    }, $str);
}

// ascii
function asc_unserialize($serial_str) {
    $serial_str = preg_replace('!s:(\d+):"(.*?)";!se', '"s:".strlen("$2").":\"$2\";"', $serial_str);
    $serial_str = str_replace("\r", "", $serial_str);
    return unserialize($serial_str);
}

/*
 * 
 * 生成短链接
 */

function shorturl($url, $domain = '') {
    $charset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    $key = C('AUTH_KEY');
    $urlhash = md5($key . $url);
    $len = strlen($urlhash);

    #将加密后的串分成4段，每段4字节，对每段进行计算，一共可以生成四组短连接
    for ($i = 0; $i < 4; $i++) {
        $urlhash_piece = substr($urlhash, $i * $len / 4, $len / 4);
        #将分段的位与0x3fffffff做位与，0x3fffffff表示二进制数的30个1，即30位以后的加密串都归零
        $hex = hexdec($urlhash_piece) & 0x3fffffff; #此处需要用到hexdec()将16进制字符串转为10进制数值型，否则运算会不正常

        $short_url = $domain . "s/";
        #生成6位短连接
        for ($j = 0; $j < 6; $j++) {
            #将得到的值与0x0000003d,3d为61，即charset的坐标最大值
            $short_url .= $charset[$hex & 0x0000003d];
            #循环完以后将hex右移5位
            $hex = $hex >> 5;
        }

        $short_url_list[] = $short_url;
    }

    return $short_url_list;
}

/*
 *  ip地址转物理地址
 */

function GetIpLookup($ip = '') {
    if (empty($ip)) {
        return '';
    }
    if ($ip == '127.0.0.1') {
        return '本地测试ip';
    }

    $res = curl_get('http://api.map.baidu.com/location/ip?ip=' . $ip . '&ak=abDsBedrGw46lo1CyQuwZs9magjV5gSf&coor=');
    $user_json = json_decode($res, true);
    return $user_json['content']['address'];
}

function curl_get($url) {
    $ch = curl_init();
    $timeout = 300;
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    $res = curl_exec($ch);

    if (curl_errno($ch)) {
        echo 'Curl error: ' . curl_error($ch);
    }
    curl_close($ch);
    return $res;
}

/* 校验URL地址 */

function checkDomain($domain) {
    return ereg("^(http|ftp)s? ://(www\.)?.+(com|net|org)$", $domain);
}

/**
 * 
 * 文件上传
 */
function uploadify() {
    $config = C('oss');
    $file = isset($_FILES['Filedata']) ? : end($_FILES);
    $ext = substr(strrchr($file['name'], '.'), 0);
    $object = 'images/' . uniqid() . $ext;

    $client = new OSS\OssClient($config['access_key_id'], $config['access_key_secret'], $config['endpoint']);
    $options = [
        'Content-Length' => $file['size'],
    ];
    if (!$client->doesBucketExist($config['bucket'])) {
        $client->createBucket($config['bucket']);
        $client->putBucketAcl($config['bucket'], 'public-read');
    }
    $AclStr = $client->getBucketAcl($config['bucket']);
    if ($AclStr == 'private') {
        $client->putBucketAcl($config['bucket'], 'public-read');
    }
    $ret = $client->uploadFile($config['bucket'], $object, $file['tmp_name'], $options);
    if ($parms == 2) {
        if ($type == 'json') {
            $return = array(
                'error' => '',
                'fileName' => $file['name'],
                'uploaded' => 1,
                'url' => $ret['info']['url']
            );
            exit(json_encode($return));
        } else {
            exit("<script>window.parent.CKEDITOR.tools.callFunction(" . $funcNum . ", \"" . $ret['info']['url'] . "\");</script>");
            exit;
        }
    } else {
        echo $ret['info']['url'];
    }
}

function uploadBase64toOss($img, $filename, $ext = 'jpg', $dir = 'images', $img_size = '3145728') {
    $fileBase64 = explode(',', $img);
    $fileBaseDecode = $fileBase64['1'];
    $imgname = base64_decode($fileBaseDecode);
    //设置临时存放目录
    $path = BASE_PATH . '/attachs/' . 'temp/';
    if (!file_exists($path)) {
        if (!mkdir($path, 0777, true)) {
            echo '创建文件夹失败';
            die();
        }
    }
    $file_name = $path . $filename;
    if (!file_exists($file_name)) {
        if (!touch($file_name)) {
            echo '创建文件失败';
            die();
        }
        if (!chmod($file_name, 0777)) {
            echo '修改权限失败';
            die();
        }
    }
    
    $output_file = $filename;
    $path = $path . $output_file;
    file_put_contents($file_name, $imgname);

    $object = $dir . '/' . $filename . '.' . $ext;
    $config = C('oss');
    $client = new OSS\OssClient($config['access_key_id'], $config['access_key_secret'], $config['endpoint']);
    $options = [
        'Content-Length' => $img_size['img_size'],
    ];
    $ret = $client->uploadFile($config['bucket'], $object, $path, $options);
    if ($ret) {
        unlink($path);
        echo $ret['info']['url'];
    } else {
        echo "上传失败";
    }
}

/*
 * 章节内容html标签过滤
 */

function stpstr($content = '') {
    $content = htmlspecialchars_decode($content);
    $content = str_replace("<br/><br/>", "<p/>", $content);
//    $content = str_replace("<br/>", "", $content);
//    $content = str_replace("<p></p>", "", $content);
//    $content = str_replace("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;", "&nbsp;&nbsp;&nbsp;&nbsp;", $content);
//    $parten = '/[^p]&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;/';
//    $content = str_replace("&nbsp;&nbsp;&nbsp;&nbsp;", "<p>&nbsp;&nbsp;&nbsp;&nbsp;", $content);
//    pr($content);
    return $content;
}

/*
 * curl 请求
 */

function http_curl($url, $type = 'get', $res = 'json', $arr = '') {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    if ($type == 'post') {
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $arr);
    }
    $output = curl_exec($ch);
    if ($output === FALSE) {
        echo "cURL Error: " . curl_error($ch);
    }
//   $info = curl_getinfo($ch);
    curl_close($ch);
    if ($res == 'json') {
        if (curl_error($ch)) {
            return curl_error($ch);
        } else {
            return json_decode($output, true);
        }
    }
    return $output;
}

/*
 * 计算中文字数
 */
function count_word($str){     
    $str = preg_replace('/[\x80-\xff]{1,3}/', ' ', $str,-1,$n); 
    $n += str_word_count($str); 
    return $n; 
}

function BA($url = '', $vars = '', $title = '', $mini = "", $class = "", $width = '', $height = '') {
	static $admin;
    if(empty($admin)){
		$admin = session('admin');
		$admin['menu_list'] = D('RoleMaps')->getMenuIdsByRoleId($admin['role_id']);
    }
//	if ($admin['role_id'] != 1) {
//        $menu = D('Menu')->fetchAll();
//        $menu_id = 0;
//        foreach ($menu as $k => $v) {
//            if ($v['menu_action'] == $url) {
//                $menu_id = (int) $k;
//            }
//        }
//        if (empty($menu_id) || !isset($admin['menu_list'][$menu_id])) {
//            $url = 'javascript:void(0);';
//            $title = '未授权';
//            $mini = '';
//        } else {
//            $url = U($url, $vars);
//        }
//    } else {
        $url = U($url, $vars);
//    }

    //权限判断 暂时忽略，后面补充
    $m = $c = $h = $w = '';
    if (!empty($mini)) {
        $m = ' mini="' . $mini . '"  ';
    }
    if (!empty($class)) {
        $c = ' class="' . $class . ' " ';
    }
    if (!empty($width)) {
        $w = ' w="' . $width . ' " ';
    }
    if (!empty($width)) {
        $h = ' h="' . $height . ' " ';
    }

    return '<a href="' . $url . '" ' . $m . $c . $w . $h . ' >' . $title . '</a>';
}